package com.itouch.bracelet.activity;

import io.rong.imkit.RongIM;
import io.rong.imkit.RongIM.GetFriendsProvider;
import io.rong.imkit.model.UIUserInfo;
import io.rong.imlib.RongIMClient.UserInfo;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.itouch.bracelet.R;
import com.itouch.bracelet.adapter.ContactAdapter;
import com.itouch.bracelet.bean.Contact;
import com.itouch.bracelet.bean.ContactResult;
import com.itouch.bracelet.cache.ContactListCache;
import com.itouch.bracelet.cache.UserCache;
import com.itouch.bracelet.diseaseinfo.Constants;
import com.itouch.util.JsonAndPhpUtil;
import com.itouch.widget.PinnedSectionListView;
import com.itouch.widget.SideBar;
import com.itouch.widget.SideBar.OnTouchingLetterChangedListener;

/**
 * cocoaSJ
 */
public class ContactActivity extends BaseActivity implements OnClickListener,
		OnItemClickListener, GetFriendsProvider {

	private static final String LOG_TAG = "ContactActivity";
	private static final int NEW_REQUEST = 0x1234;
	private Handler mHandler;
	private PinnedSectionListView listview;
	private ContactAdapter adapter;
	private ArrayList<Contact> list;
	private int position = 0;
	private SideBar sideBar;
	private TextView dialog;
	private List<String> indexSB = null;
	private List<Integer> selectionPostion = new ArrayList<Integer>();

	String[] iChart = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K",
			"L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X",
			"Y", "Z", "#" };
	private String[] sss;
	private ArrayList<Contact> tempList;
	private ArrayList<Contact> cache;
	private RelativeLayout nearby;
	private RelativeLayout new_friend;
	private RelativeLayout group;

	
	
	@Override
	protected int setContentViewById() {
		return R.layout.fragment_im;
	}

	@Override
	protected void initViews() {
		listview = (PinnedSectionListView) this.findViewById(
				R.id.listview);
		list = new ArrayList<Contact>();
		tempList = new ArrayList<Contact>();
		adapter = new ContactAdapter(this, list);
		listview.setAdapter(adapter);
		listview.setOnItemClickListener(this);
		getFriend();
		
		mHandler = new Handler();

		nearby=(RelativeLayout)findViewById(R.id.nearby);
		group=(RelativeLayout)findViewById(R.id.group);
		new_friend=(RelativeLayout)findViewById(R.id.new_friend);
		nearby.setOnClickListener(this);
		new_friend.setOnClickListener(this);
		group.setOnClickListener(this);
		
		
		
	}

	@Override
	protected void initData() {
//		cache = ContactListCache.getOauth(this);
//		if (cache != null && cache.size() > 0) {
//			setList(cache);
//		} else {
		String id=UserCache.getOauth(this).getUserId();
			new GetUserListAsync(this).execute(id);
//		}
		
	}
	
	
	
	@Override
	protected void onActivityResult(int arg0, int arg1, Intent arg2) {
		// TODO Auto-generated method stub
		super.onActivityResult(arg0, arg1, arg2);
		if(NEW_REQUEST==arg0){
			String id=UserCache.getOauth(this).getUserId();
			new GetUserListAsync(this).execute(id);
		}
		
		
	}
	

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		if (list == null) {
			return;
		}

		try {
			final Contact a = list.get(arg2);
			if (a.getId() == null) {
				return;
			}

			  mHandler.post(new Runnable() {
                  @Override
                  public void run() {

                      RongIM.getInstance().startPrivateChat(
          					context, a.getReceiver(), a.getReceiverName());
                  }
              }
          );
			
			
			
		} catch (ArrayIndexOutOfBoundsException e) {

		}

	}

//	private void initGroupInfo() {
//
//		HashMap<String, RongIMClient.Group> groupM = new HashMap<String, RongIMClient.Group>();
//
//		List<RongIMClient.Group> groups = new ArrayList<RongIMClient.Group>();
//
//		Iterator iterator = groupM.values().iterator();
//
//		while (iterator.hasNext()) {
//			groups.add((RongIMClient.Group) iterator.next());
//		}
//		if (RongIM.getInstance() != null) {
//			RongIM.getInstance().syncGroup(groups,
//					new RongIM.OperationCallback() {
//
//						@Override
//						public void onSuccess() {
//							Log.e("syncGroup",
//									"=============syncGroup====onSuccess===========");
//						}
//
//						@Override
//						public void onError(ErrorCode errorCode) {
//							Log.e("syncGroup",
//									"=============syncGroup====onError==========="
//											+ errorCode);
//						}
//					});
//		}
//	}

	

	@Override
	public void onClick(View arg0) {
		Intent it =null;
		switch (arg0.getId()) {
		case R.id.nearby:
			 it = new Intent(this, NearByActivity.class);
			 startActivity(it);
			break;
		case R.id.group:
			 it = new Intent(this, GroupActivity.class);
			startActivity(it);
			break;
		case R.id.new_friend:
			 it = new Intent(this, NewFriendsActivity.class);
			 startActivityForResult(it,NEW_REQUEST);
			break;

		default:
			break;
		}

	}



	class GetUserListAsync extends AsyncTask<String, String, String> {

		private Context context;

		public GetUserListAsync(Context context) {
			super();
			this.context = context;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			list .clear();
			tempList .clear();
			show();
		}

		@Override
		protected String doInBackground(String... params) {
			List<NameValuePair> lists = new ArrayList<NameValuePair>();
			lists.add(new BasicNameValuePair("id", params[0]));
			String ss = JsonAndPhpUtil.postHttpData(Constants.GET_FRIENDS_BY_ID, lists, context);
			Log.i(LOG_TAG, LOG_TAG + ss);
			return ss;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			disMiss();
			if (result!=null&&result.length()>10) {
				ContactResult a = new Gson().fromJson(result,
						ContactResult.class);
				if (a != null && a.isFlag()) {
					tempList.addAll(a.getRows());
					setList(tempList);
					ContactListCache.saveOAuth(a.getRows(), context);
					getFriend();
				}
			}
		}
	}

	private void getFriend() {
		RongIM.getInstance().setGetFriendsProvider(this);
	}

	/**
	 * 设置listview 和sidebar的数据，需要优化
	 * 
	 * @param listParam
	 */
	private void setList(ArrayList<Contact> listParam) {
		indexSB = new ArrayList<String>();
		for (int i = 0; i < iChart.length; i++) {
			String s = iChart[i].toLowerCase();
			list.add(new Contact(s));
			selectionPostion.add(list.size() - 1);
			indexSB.add(s);
			int temp = 0;
			int size = listParam.size();
			for (int j = 0; j < size; j++) {
				Contact c = listParam.get(j);
				if (c.getReceiverJM().startsWith(s)) {
					list.add(c);
					temp++;
				}
			}
			if (temp == 0) {
				list.remove(list.size() - 1);
				indexSB.remove(indexSB.size() - 1);
				selectionPostion.remove(selectionPostion.size() - 1);
			}
		}
		adapter.notifyDataSetChanged();
		sss = new String[indexSB.size()];
		for (int i = 0; i < indexSB.size(); i++) {
			String s = indexSB.get(i);
			sss[i] = s;
		}
		if (sss != null && sss.length > 0) {
			sideBar = (SideBar) this.findViewById(R.id.sidrbar);
			dialog = (TextView) this.findViewById(R.id.dialog);
			sideBar.setB(sss);
			sideBar.setTextView(dialog);
			sideBar.setOnTouchingLetterChangedListener(new OnTouchingLetterChangedListener() {

				@Override
				public void onTouchingLetterChanged(String s) {
					if (sss == null) {
						return;
					}
					for (int i = 0; i < sss.length; i++) {
						if (sss[i].equals(s)) {
							listview.setSelection(selectionPostion.get(i));
							break;
						}
					}
				}
			});
		}
	}

	@Override
	public List<UserInfo> getFriends() {
		if (cache != null && cache.size() > 0) {
			List<UserInfo> list = new ArrayList<UserInfo>();

			for (int i = 0; i < cache.size(); i++) {
				Contact a = cache.get(i);
				UIUserInfo info = new UIUserInfo(a.getId(), a.getReceiverName(),
						" ");
				list.add(info);
			}
			return list;
		}

		return null;
	}

	

	
}